#/bin/python
#coding:utf8
'''
Created on 2011-4-30

@author: mark
'''
from __future__ import with_statement

import os
import web
import config
from model import user
from model import problem
from model import ptype
from model import answer
from model import district
from util import basic
from util import json
from util import auth
from util import page


tp = config.template_user
tp_user = config.template_user
db = config.database

class register:
    def POST(self):
        '''
            the passwd is md5 hashed
        '''
        try:
            with db.transaction():
                i = web.input()
                _email = i['email']
                _passwd = basic.hash2md5(i['passwd1'])
                _nickname = i['nickname']
                _captcha =i['captcha']
                
        #        if not auth.checkCaptcha(_captcha):
        #            return tp.register(message=u'验证码错误')
                
                uid = user.createuser(_email, _passwd, _nickname)
                
                if uid:
                    return tp.register_succ()
        except Exception,e:
            return e
        
    def GET(self):
        return tp.register()

class loginuser:
    def POST(self):
        i = web.input(remember="off")
        _email = i['email']
        _passwd = basic.hash2md5(i['passwd'])
        _remember = i['remember']
        
        current_user = user.getuserbymailandpass(_email, _passwd)
        if current_user:
            web.ctx.session['current_user'] = current_user
            
            #记录cookie来记住用户的登录
            if _remember == "on":
                auth.setcookie(current_user, True)
                
            web.seeother('/userhome/%s/' % current_user['uid'])
            
        else:
            return tp.login({"msg":u"用户名和密码错误"})

    def GET(self):
        return tp.login()
    
class logout:
    def GET(self):
        '''
            logout ,then go to the anonymous page
        '''
        current_user = web.ctx.session['current_user']
        user.updatellt(current_user.uid)
        web.ctx.session.kill()
        auth.setLogoutCookie()
        web.seeother("/")
        
class emailAvail():
    def GET(self):
        i = web.input()
        email = i['email']
        result = user.checkemail(email) is not None
        return json.write({"canuse":result})
        
#用户根目录
class userhome:
    def GET(self, uid):
        client_user = web.ctx.session['current_user']
        if not client_user:
            return web.seeother("/")
        
        if not uid:
            return web.seeother("/")
        
        i = web.input(start=None)
        start = i['start']
        s = 0 if start is None else int(start)
        
        myproblems = problem.getMyProblemsForUserhome(uid, s)
        max_resuts = ptype.getMyProblemCount(uid)
        homeuser = user.getuserbyid(uid) # homeuser -> /usrhome/{uid}
        current_user = web.ctx.session["current_user"]
        
        pages = page.get_paging(s, max_resuts)
        
        monthHotProblems = problem.getMonthHotProblems(10)
        weekHotProblems = problem.getWeekHotProblems(10)
        context = {"myproblems":myproblems, \
                 "pages":pages, \
				 "user":homeuser, \
                 "current_user" :current_user , \
                 "urlbase":"/userhome/%s/myproblem?start=" % uid, \
                 "focusurl":"/userhome/%s/myfocus" % uid,\
                 "monthHotProblems":monthHotProblems,\
                 "weekHotProblems":weekHotProblems }
        
        return tp.userhome(context)       
    
class modifyPassword:
    @auth.login
    def POST(self):
        i = web.input()
        oldpasswd = i['oldpasswd']
        newpasswd = i['newpasswd']
        
        current_user = web.ctx.session['current_user']
        uid = current_user['uid']
        
        if basic.hash2md5(oldpasswd) != current_user['passwd']:
            return tp.modifypasswd({"msg":u"老密码错误啦"})
        else:
            res = user.updatepasswd(uid, basic.hash2md5(newpasswd))
            current_user = user.getuserbyid(uid)
            web.ctx.session['current_user'] = current_user
            
            if res:
                return web.seeother('/account')
    
    @auth.login
    def GET(self):
        return tp.modifypasswd()

class changeLogo:
    @auth.login
    def GET(self):
        current_user = web.ctx.session['current_user']
        context = {"user":current_user}
        return tp.uploadImage(context)
    
    @auth.login
    def POST(self):
        i = web.input(userlogo={})
        current_user = web.ctx.session['current_user']
        uid = int(current_user.uid)
        
        if 'userlogo' in i:
            filename = basic.uphotoname(i['userlogo'].filename, uid)
            filepath = os.path.join(config.userlogo_path,filename)
            showpath = os.path.join(config.user_logo_path, filename)
            try:
                fout = open(filepath, 'wb')
                fout.write(i.userlogo.file.read())
                fout.close()
                user.updatelogo(uid, showpath)
                auth.updateSessionUser(uid)
            except Exception,e:
                print e
                return json.write({"error":0, "msg":"Upload Error"})
        #return json.write({"error":str(1), "msg":showpath})
        
        return web.seeother("/account/")
    
class UserInfo:
    @auth.login
    def GET(self):
        '''
            get account info ,and update 
        '''
        
        current_user = web.ctx.session['current_user']
        allDistricts = district.getAllDistricts()
        monthHotProblems = problem.getMonthHotProblems(10)
        weekHotProblems = problem.getWeekHotProblems(10)
        
        context = {"user":current_user, \
                   "allDistricts":allDistricts, \
                   "monthHotProblems":monthHotProblems,\
                   "weekHotProblems":weekHotProblems
                   }
        return tp.account(context)
        
    @auth.login 
    def POST(self):
        try:
            with db.transaction():
                current_user = web.ctx.session['current_user']
                uid = int(current_user['uid'])
                
                i = web.input()
                nickname = i['nickname']
                cellphone = i['cellphone']
                district = i['district']
                
                res = user.updateUserInfo(uid, nickname, district, cellphone)
                
                #update session
                
                auth.updateSessionUser(uid)
                
                return web.seeother('/userhome/%s/' % current_user['uid'])
            
        except Exception,e:
            return e


    
class userproblem:
    @auth.login
    def GET(self):
        current_user = web.ctx.session['current_user']
        i = web.input(start=None)
        start = i['start']
        s = 0 if start is None else int(start)
        myproblems = problem.getMyProblems(current_user.uid, s)
        max_resuts = ptype.getMyProblemCount(current_user.uid)
        monthHotProblems = problem.getMonthHotProblems(10)
        weekHotProblems = problem.getWeekHotProblems(10)
        pages = page.get_paging(s, max_resuts)
        context = {"problems":myproblems, \
                 "pages":pages, \
                 "urlbase":"/type/1?start=", \
                 "monthHotProblems":monthHotProblems,\
                 "weekHotProblems":weekHotProblems}
        return tp.userhome(context)
    
class MySponserProblem:
    def GET(self, uid):
        i = web.input(start=None)
        start = i['start']
        try:
            start = 0 if not start else int(start)
        except Exception:
            start = 0

        problems = problem.getMyProblemsForUserhome(uid, start)
        problemcount = problem.getMyProblemCount(uid)
        pages = page.get_paging(start, problemcount)
        current_user = web.ctx.session['current_user']
        homeuser = user.getuserbyid(uid)
        monthHotProblems = problem._getMonthHotProblems(10)
        weekHotProblems = problem._getWeekHotProblems(10)
        types = ptype.getTypes()
        
        context = {"myproblems":problems, \
                   "current_user":current_user, \
                   "user":homeuser,\
                   "pages":pages, \
                   "urlbase":"/userhome/%s/myproblem?start=" % uid, \
                   "focusurl":"/userhome/%s/myfocus" % uid,\
                   "monthHotProblems":monthHotProblems,\
                   "weekHotProblems":weekHotProblems,\
                   "types":types}
        
        return tp_user.userhome(context)

class MyFocusProblem:
    def GET(self, uid):
        i = web.input(start=None)
        start = i['start']
        
        try:
            start = 0 if not start else int(start)
        except Exception:
            start = 0
            
        focusproblems = problem.getMyFocusProblem(uid, start)
        problemcount = answer.getMyFocusProblemCount(uid)
        pages = page.get_paging(start, problemcount)
        
        current_user = web.ctx.session['current_user']
        homeuser = user.getuserbyid(uid)
        monthHotProblems = problem._getMonthHotProblems(10)
        weekHotProblems = problem._getWeekHotProblems(10)
        types = ptype.getTypes()
        context = {"fcproblems":focusproblems, \
                   "current_user":current_user, \
                   "homeuser":homeuser,\
                   "pages":pages, \
                   "urlbase":"/userhome/%s/myfocus?start=" % uid, \
                   "sponserurl":"/userhome/%s/myproblem" % uid, \
                   "monthHotProblems":monthHotProblems,\
                   "weekHotProblems":weekHotProblems,\
                   "types":types}
        
        return tp.userhome2(context)
